<?php
	class FileUploadHandler {
		private $m_regex = "/jpg|jpeg|gif|png|txt/";
		private $m_dir = "../fileUpload/files/";
		const EVERYTHING_WENT_BETTER_THEN_EXPECTED = 0;
		const GENERIC_ERROR = 1;
		const EXTENSION_NOT_SUPPORTED = 2;
		const FAILED_TO_MOVE = 3;
		
		/**
		 * Uploads a file
		 * @param binary $file
		 * @return int $errorCode
		 */
		public function UploadFile(Array $file) {
			$i = 0;
			$tempName;
			$ext;
			
			if ($file["error"] > 0) {
				return self::GENERIC_ERROR;
			}
			
			$ext = explode(".", $file["name"]);
			if (!preg_match($this->m_regex, end($ext))) {
				return self::EXTENSION_NOT_SUPPORTED;
			}
			
			while (file_exists($this->m_dir.$file["name"])) {
				$tempName = $file["name"];
				$tempName = $i.$tempName;
				if (file_exists($this->m_dir.$tempName)) {
					$i++;
				} else {
					$file["name"] = $tempName;
				}
			}
			
			if (!move_uploaded_file($file["tmp_name"], $this->m_dir.$file["name"])) {
				return self::FAILED_TO_MOVE;
			}

			return self::EVERYTHING_WENT_BETTER_THEN_EXPECTED;
		}
		
		/**
		 * Gets a list of files
		 * @return array files
		 */
		public function GetFileList() {
			$fileArray = null;
			$i = 0;
			
			if (is_dir($this->m_dir)) {
				if ($dh = opendir($this->m_dir)) {
					while (($file = readdir($dh)) !== false) {
						if (preg_match($this->m_regex, pathinfo($this->m_dir.$file, PATHINFO_EXTENSION))) {
							$fileArray[$i] = array($this->m_dir.$file, $file, pathinfo($this->m_dir.$file, PATHINFO_EXTENSION), strval(intval(filesize($this->m_dir.$file)/1024))." Kb");
							$i++;
						}
					}
					closedir($dh);
				}
			}
			
			return $fileArray;
		}
	}
?>